import tkinter as tk
from tkinter import ttk, messagebox, scrolledtext, simpledialog
import datetime
import threading
import random
import math
from config_manager import ConfigManager
from login_manager import LoginManager
from danmu_sender import DanmuSenderManager
from gift_listener import GiftListener
from utils import get_current_time
import os
from PIL import Image, ImageTk  # 需要安装Pillow库: pip install pillow
from io import BytesIO
import requests
import json
# 初始化数据管理器
from gift_data_manager import GiftDataManager  # 导入数据管理器
from tkinter import Listbox  # 从 tkinter 导入

class BilibiliDanmuApp:
    def __init__(self, root: tk.Tk, config_manager: ConfigManager, login_manager: LoginManager):
        self.root = root
        self.config_manager = config_manager  # 配置管理器
        self.login_manager = login_manager  # 登录管理器
        self._init_vars()  # 初始化变量
        self._create_widgets()  # 创建GUI组件
        self.update_login_status()  # 初始更新登录状态
        self._bind_events()  # 绑定事件

    def _init_vars(self):
        """初始化全局变量"""
        # 弹幕发送相关
        self.danmu_manager = DanmuSenderManager(
            cookies=self.login_manager.cookies,
            csrf_token=self.login_manager.csrf_token
        )
        self.is_sending = False  # 弹幕发送状态
        self.send_thread = None  # 弹幕发送线程
        self.next_send_time = None  # 下次发送时间

        # 礼物监听相关
        self.gift_listener = None  # 礼物监听实例
        # 【删除残留的listen_room_var，改用Text组件直接操作】

        # 登录状态相关
        self.login_status_var = tk.StringVar(value="未登录")
        self.user_info_var = tk.StringVar(value="用户ID: 未登录")
        self.avatar_photo = None  # 头像图片对象

        self.avatar_path = os.path.join("data", "avatars")  # 头像保存路径
        os.makedirs(self.avatar_path, exist_ok=True)  # 创建头像目录

    def _create_widgets(self):
        """创建所有GUI组件"""
        # 1. 选项卡容器
        self.notebook = ttk.Notebook(self.root)
        self.notebook.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

        # 2. 创建各选项卡
        self._create_login_tab()  # 登录选项卡
        self._create_send_tab()  # 弹幕发送选项卡
        self._create_listener_tab()  # 礼物监听选项卡
        self._create_query_tab()  # 测试盲盒查询选项卡
        self._create_comprehensive_tab()  # 综合功能选项卡
        self._create_log_tab()  # 日志选项卡

        # 3. 状态栏
        self.status_var = tk.StringVar(value="就绪")
        self.status_bar = ttk.Label(
            self.root, textvariable=self.status_var, relief=tk.SUNKEN, anchor=tk.W
        )
        self.status_bar.pack(side=tk.BOTTOM, fill=tk.X)

        # 4. 加载配置到控件
        self._load_config_to_widgets()

    def _create_login_tab(self):
        """创建登录选项卡（Cookie登录+二维码登录）"""
        self.login_frame = ttk.Frame(self.notebook, padding=10)
        self.notebook.add(self.login_frame, text="登录")

        # ------------------- Cookie登录区域 -------------------
        # cookie_frame = ttk.LabelFrame(self.login_frame, text="Cookie登录", padding=10)
        # cookie_frame.pack(fill=tk.X, pady=5)
        #
        # ttk.Label(cookie_frame, text="Cookie字符串:").grid(row=0, column=0, sticky=tk.W, pady=5)
        # self.cookie_var = tk.StringVar()
        # self.cookie_entry = ttk.Entry(cookie_frame, textvariable=self.cookie_var, width=50)
        # self.cookie_entry.grid(row=0, column=1, padx=5, pady=5, sticky=tk.EW)
        #
        # # Cookie操作按钮
        # btn_frame = ttk.Frame(cookie_frame)
        # btn_frame.grid(row=0, column=2, padx=5, pady=5)
        # ttk.Button(btn_frame, text="导入", command=self.import_cookie).pack(pady=2)
        # ttk.Button(btn_frame, text="保存", command=self.save_cookie).pack(pady=2)
        # ttk.Button(btn_frame, text="测试", command=self.test_cookie).pack(pady=2)

        # ------------------- 二维码登录区域 -------------------
        qr_frame = ttk.LabelFrame(self.login_frame, text="二维码登录", padding=10)
        qr_frame.pack(fill=tk.X, pady=5)

        self.qr_label = ttk.Label(qr_frame, text="点击下方按钮生成二维码")
        self.qr_label.pack(pady=10)
        ttk.Button(qr_frame, text="生成二维码", command=self.generate_qr_code).pack(pady=5)

        # ------------------- 登录状态区域 -------------------
        # 登录状态区域（包含头像）
        status_frame = ttk.LabelFrame(self.login_frame, text="登录状态", padding=10)
        status_frame.pack(fill=tk.X, pady=5)

        # 头像区域（左侧）
        self.avatar_label = ttk.Label(status_frame)
        self.avatar_label.grid(row=0, column=0, rowspan=3, padx=10, pady=5)

        # 状态信息（右侧）
        ttk.Label(status_frame, textvariable=self.login_status_var).grid(row=0, column=1, sticky=tk.W, pady=2)
        ttk.Label(status_frame, textvariable=self.user_info_var).grid(row=1, column=1, sticky=tk.W, pady=2)

        # 清除登录按钮
        ttk.Button(status_frame, text="清除登录", command=self.clear_cookie).grid(
            row=2, column=1, sticky=tk.W, pady=5, padx=0
        )

        # 调整列权重，让信息区域自适应宽度
        status_frame.columnconfigure(1, weight=1)

    def _create_send_tab(self):
        """创建弹幕发送选项卡（房间设置+内容+间隔）"""
        self.send_frame = ttk.Frame(self.notebook, padding=10)
        self.notebook.add(self.send_frame, text="弹幕发送")

        # ------------------- 房间设置 -------------------
        room_frame = ttk.LabelFrame(self.send_frame, text="发送目标房间", padding=10)
        room_frame.pack(fill=tk.X, pady=5)

        ttk.Label(room_frame, text="房间ID:").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.room_ids_var = tk.StringVar()
        self.room_ids_entry = ttk.Entry(room_frame, textvariable=self.room_ids_var, width=50)
        self.room_ids_entry.grid(row=0, column=1, padx=5, pady=5, sticky=tk.EW)
        self.room_ids_entry.bind("<FocusOut>", self.save_send_settings)

        # ------------------- 弹幕内容 -------------------
        danmu_frame = ttk.LabelFrame(self.send_frame, text="弹幕内容", padding=10)
        danmu_frame.pack(fill=tk.BOTH, expand=True, pady=5)

        ttk.Label(danmu_frame, text="弹幕内容(每行一条):").pack(anchor=tk.W)
        self.danmu_text = scrolledtext.ScrolledText(danmu_frame, height=6)
        self.danmu_text.pack(fill=tk.BOTH, expand=True, pady=5)
        self.danmu_text.bind("<FocusOut>", self.save_send_settings)

        # ------------------- 发送间隔 -------------------
        interval_frame = ttk.LabelFrame(self.send_frame, text="发送间隔", padding=10)
        interval_frame.pack(fill=tk.X, pady=5)

        # 最小间隔
        ttk.Label(interval_frame, text="最小间隔(秒):").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.min_interval_var = tk.StringVar()
        self.min_interval_entry = ttk.Entry(interval_frame, textvariable=self.min_interval_var, width=10)
        self.min_interval_entry.grid(row=0, column=1, padx=5, pady=5, sticky=tk.W)
        self.min_interval_entry.bind("<FocusOut>", self.save_send_settings)

        # 最大间隔
        ttk.Label(interval_frame, text="最大间隔(秒):").grid(row=0, column=2, sticky=tk.W, pady=5)
        self.max_interval_var = tk.StringVar()
        self.max_interval_entry = ttk.Entry(interval_frame, textvariable=self.max_interval_var, width=10)
        self.max_interval_entry.grid(row=0, column=3, padx=5, pady=5, sticky=tk.W)
        self.max_interval_entry.bind("<FocusOut>", self.save_send_settings)

        # 下次发送时间
        self.next_time_var = tk.StringVar(value="下次发送时间: 未开始")
        ttk.Label(interval_frame, textvariable=self.next_time_var).grid(row=1, column=0, columnspan=4, sticky=tk.W,
                                                                        pady=5)

        # ------------------- 控制按钮 -------------------
        btn_frame = ttk.Frame(self.send_frame)
        btn_frame.pack(fill=tk.X, pady=10)

        self.start_send_btn = ttk.Button(btn_frame, text="开始发送", command=self.start_sending)
        self.start_send_btn.pack(side=tk.LEFT, padx=5)

        self.stop_send_btn = ttk.Button(btn_frame, text="停止发送", command=self.stop_sending, state=tk.DISABLED)
        self.stop_send_btn.pack(side=tk.LEFT, padx=5)

        ttk.Button(btn_frame, text="测试发送", command=self.test_sending).pack(side=tk.LEFT, padx=5)

    def _create_listener_tab(self):
        """创建礼物监听推送选项卡（已修正为多行文本框）"""
        self.listener_frame = ttk.Frame(self.notebook, padding=10)
        self.notebook.add(self.listener_frame, text="礼物监听推送")

        # ------------------- 监听房间设置（多行文本框核心修改） -------------------
        listen_frame = ttk.LabelFrame(self.listener_frame, text="监听房间", padding=10)
        listen_frame.pack(fill=tk.X, pady=5)

        ttk.Label(listen_frame, text="监听房间ID(多个用逗号/换行分隔):").grid(row=0, column=0, sticky=tk.W, pady=5)
        # 多行文本框：width=50（宽度）、height=3（显示3行），支持换行输入
        self.listen_room_text = tk.Text(listen_frame, width=50, height=10)
        self.listen_room_text.grid(row=0, column=1, padx=5, pady=5, sticky=tk.EW)
        # 焦点离开时保存设置（保留原逻辑）
        self.listen_room_text.bind("<FocusOut>", self.save_listener_settings)

        # ------------------- 推送目标设置 -------------------
        push_frame = ttk.LabelFrame(self.listener_frame, text="推送目标", padding=10)
        push_frame.pack(fill=tk.X, pady=5)

        ttk.Label(push_frame, text="推送目标房间ID:").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.push_target_var = tk.StringVar()
        self.push_target_entry = ttk.Entry(push_frame, textvariable=self.push_target_var, width=50)
        self.push_target_entry.grid(row=0, column=1, padx=5, pady=5, sticky=tk.EW)
        self.push_target_entry.bind("<FocusOut>", self.save_listener_settings)

        # ------------------- 控制按钮 -------------------
        btn_frame = ttk.Frame(self.listener_frame)
        btn_frame.pack(fill=tk.X, pady=10)

        self.start_listen_btn = ttk.Button(btn_frame, text="开始监听推送", command=self.start_listener)
        self.start_listen_btn.pack(side=tk.LEFT, padx=5)

        self.stop_listen_btn = ttk.Button(btn_frame, text="停止监听推送", command=self.stop_listener, state=tk.DISABLED)
        self.stop_listen_btn.pack(side=tk.LEFT, padx=5)

    def _create_query_tab(self):
        """创建盲盒数据查询选项卡"""
        self.query_frame = ttk.Frame(self.notebook, padding=10)
        self.notebook.add(self.query_frame, text="盲盒数据查询")

        self.data_manager = GiftDataManager()

        # ------------------- 查询条件区域 -------------------
        query_cond_frame = ttk.LabelFrame(self.query_frame, text="查询条件", padding=10)
        query_cond_frame.pack(fill=tk.X, pady=5)

        # UID查询
        ttk.Label(query_cond_frame, text="用户UID:").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.query_uid_var = tk.StringVar()
        self.query_uid_entry = ttk.Entry(query_cond_frame, textvariable=self.query_uid_var, width=20)
        self.query_uid_entry.grid(row=0, column=1, padx=5, pady=5, sticky=tk.W)

        # 用户名查询
        ttk.Label(query_cond_frame, text="用户名:").grid(row=0, column=2, sticky=tk.W, pady=5)
        self.query_uname_var = tk.StringVar()
        self.query_uname_entry = ttk.Entry(query_cond_frame, textvariable=self.query_uname_var, width=20)
        self.query_uname_entry.grid(row=0, column=3, padx=5, pady=5, sticky=tk.W)

        # 查询按钮
        btn_frame = ttk.Frame(query_cond_frame)
        btn_frame.grid(row=0, column=4, padx=10, pady=5)
        ttk.Button(btn_frame, text="查询", command=self.do_query).pack(side=tk.LEFT, padx=5)
        ttk.Button(btn_frame, text="清空", command=self.clear_query).pack(side=tk.LEFT, padx=5)
        # ------------------- 监听文本设置区域 提供粉丝查询接口 -------------------
        stats_frame = ttk.LabelFrame(self.query_frame, text="粉丝查询接口_触发文本", padding=10)
        stats_frame.pack(fill=tk.X, pady=5)

        self.query_lister_text_var = tk.StringVar()
        self.lister_text_entry = ttk.Entry(stats_frame, textvariable=self.query_lister_text_var, width=20)
        self.lister_text_entry.grid(row=0, column=0, padx=5, pady=5, sticky=tk.W)
          # 焦点离开时保存设置（保留原逻辑）
        self.lister_text_entry.bind("<FocusOut>", self.save_query_settings)

        self.query_lister_text_enabled = tk.BooleanVar()  # 粉丝查询接口_触发文本 默认启用
        ttk.Checkbutton(
            stats_frame,
            text="启用功能",
            variable=self.query_lister_text_enabled,
            command=lambda: self.query_on_function_toggle("粉丝查询接口", self.query_lister_text_enabled.get())
        ).grid(row=0, column=1, padx=5, pady=5, sticky=tk.W)
        # ------------------- 结果表格区域 -------------------


        # ------------------- 统计信息区域 -------------------
        stats_frame = ttk.LabelFrame(self.query_frame, text="统计信息", padding=10)
        stats_frame.pack(fill=tk.X, pady=5)

        self.stats_var = tk.StringVar(value="请先执行查询...")
        ttk.Label(stats_frame, textvariable=self.stats_var).pack(anchor=tk.W)

        # ------------------- 结果表格区域 -------------------

        result_frame = ttk.LabelFrame(self.query_frame, text="查询结果", padding=10)
        result_frame.pack(fill=tk.BOTH, expand=True, pady=5)

        # 创建表格
        columns = [
            "timestamp", "uid", "uname", "gift_name",
            "gift_num", "cost", "income", "profit"
        ]
        self.result_tree = ttk.Treeview(result_frame, columns=columns, show="headings")

        # 设置列标题
        column_labels = {
            "timestamp": "时间",
            "uid": "用户ID",
            "uname": "用户名",
            "gift_name": "礼物名称",
            "gift_num": "数量",
            "cost": "花费",
            "income": "收入",
            "profit": "盈亏"
        }
        for col in columns:
            self.result_tree.heading(col, text=column_labels[col])
            self.result_tree.column(col, width=100, anchor=tk.CENTER)

        # 添加滚动条
        scrollbar = ttk.Scrollbar(result_frame, orient=tk.VERTICAL, command=self.result_tree.yview)
        self.result_tree.configure(yscroll=scrollbar.set)
        scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.result_tree.pack(fill=tk.BOTH, expand=True)

    def _create_comprehensive_tab(self):
        """创建综合选项卡 包括进场欢迎 关注感谢 关键词@"""
        self.comprehensive_frame = ttk.Frame(self.notebook, padding=10)
        self.notebook.add(self.comprehensive_frame, text="综合功能")

        # 初始化话术存储
        self.welcome_messages = []
        self.thank_messages = []
        # 关键词-回复对，格式: {"关键词": "回复话术"}
        self.keyword_responses = {

        }

        # 创建开关状态变量
        self.welcome_enabled = tk.BooleanVar()  # 进场欢迎默认启用
        self.thank_enabled = tk.BooleanVar()  # 关注感谢默认启用
        self.keyword_enabled = tk.BooleanVar()  # 关键词@默认启用

        # 创建通用样式
        style = ttk.Style()
        style.configure("功能标题.TLabel", font=("微软雅黑", 11, "bold"))
        style.configure("TCheckbutton", font=("微软雅黑", 10))

        # 1. 进场欢迎区域
        welcome_frame = ttk.LabelFrame(self.comprehensive_frame, text="进场欢迎话术", padding=10)
        welcome_frame.pack(fill=tk.X, pady=5)

        # 欢迎话术列表标题 + 启用开关
        welcome_title_frame = ttk.Frame(welcome_frame)
        welcome_title_frame.pack(anchor=tk.W, pady=5, fill=tk.X)
        ttk.Label(welcome_title_frame, text="当前话术列表：", style="功能标题.TLabel").pack(side=tk.LEFT)
        ttk.Checkbutton(
            welcome_title_frame,
            text="启用功能",
            variable=self.welcome_enabled,
            command=lambda: self._on_function_toggle("进场欢迎", self.welcome_enabled.get())
        ).pack(side=tk.RIGHT)

        welcome_list_frame = ttk.Frame(welcome_frame)
        welcome_list_frame.pack(fill=tk.X, pady=5)

        self.welcome_listbox = tk.Listbox(welcome_list_frame, height=4)
        self.welcome_listbox.config(font=("微软雅黑", 10), bg="#ffffff", fg="#333333")
        self.welcome_listbox.pack(side=tk.LEFT, fill=tk.X, expand=True)
        welcome_scrollbar = ttk.Scrollbar(welcome_list_frame, orient=tk.VERTICAL, command=self.welcome_listbox.yview)
        welcome_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.welcome_listbox.config(yscrollcommand=welcome_scrollbar.set)

        # 欢迎话术操作区
        welcome_ops_frame = ttk.Frame(welcome_frame)
        welcome_ops_frame.pack(fill=tk.X, pady=5)

        ttk.Label(welcome_ops_frame, text="话术内容：").pack(side=tk.LEFT, padx=5)
        self.welcome_entry = ttk.Entry(welcome_ops_frame, width=50)
        self.welcome_entry.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)

        ttk.Button(welcome_ops_frame, text="添加", command=lambda: self._add_message("welcome")).pack(side=tk.LEFT,
                                                                                                      padx=2)
        ttk.Button(welcome_ops_frame, text="修改", command=lambda: self._edit_message("welcome")).pack(side=tk.LEFT,
                                                                                                       padx=2)
        ttk.Button(welcome_ops_frame, text="删除", command=lambda: self._delete_message("welcome")).pack(side=tk.LEFT,
                                                                                                         padx=2)
        # ttk.Button(welcome_ops_frame, text="随机测试", command=lambda: self._test_random_message("welcome")).pack(
        #     side=tk.LEFT, padx=2)

        # 2. 关注感谢区域
        thank_frame = ttk.LabelFrame(self.comprehensive_frame, text="关注感谢话术", padding=10)
        thank_frame.pack(fill=tk.X, pady=5)

        # 感谢话术列表标题 + 启用开关
        thank_title_frame = ttk.Frame(thank_frame)
        thank_title_frame.pack(anchor=tk.W, pady=5, fill=tk.X)
        ttk.Label(thank_title_frame, text="当前话术列表：", style="功能标题.TLabel").pack(side=tk.LEFT)
        ttk.Checkbutton(
            thank_title_frame,
            text="启用功能",
            variable=self.thank_enabled,
            command=lambda: self._on_function_toggle("关注感谢", self.thank_enabled.get())
        ).pack(side=tk.RIGHT)

        thank_list_frame = ttk.Frame(thank_frame)
        thank_list_frame.pack(fill=tk.X, pady=5)

        self.thank_listbox = tk.Listbox(thank_list_frame, height=4)
        self.thank_listbox.config(font=("微软雅黑", 10), bg="#ffffff", fg="#333333")
        self.thank_listbox.pack(side=tk.LEFT, fill=tk.X, expand=True)
        thank_scrollbar = ttk.Scrollbar(thank_list_frame, orient=tk.VERTICAL, command=self.thank_listbox.yview)
        thank_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.thank_listbox.config(yscrollcommand=thank_scrollbar.set)

        # 感谢话术操作区
        thank_ops_frame = ttk.Frame(thank_frame)
        thank_ops_frame.pack(fill=tk.X, pady=5)

        ttk.Label(thank_ops_frame, text="话术内容：").pack(side=tk.LEFT, padx=5)
        self.thank_entry = ttk.Entry(thank_ops_frame, width=50)
        self.thank_entry.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)

        ttk.Button(thank_ops_frame, text="添加", command=lambda: self._add_message("thank")).pack(side=tk.LEFT, padx=2)
        ttk.Button(thank_ops_frame, text="修改", command=lambda: self._edit_message("thank")).pack(side=tk.LEFT, padx=2)
        ttk.Button(thank_ops_frame, text="删除", command=lambda: self._delete_message("thank")).pack(side=tk.LEFT,
                                                                                                     padx=2)
        # ttk.Button(thank_ops_frame, text="随机测试", command=lambda: self._test_random_message("thank")).pack(
        #     side=tk.LEFT, padx=2)

        # 3. 关键词@区域
        keyword_frame = ttk.LabelFrame(self.comprehensive_frame, text="关键词@回复", padding=10)
        keyword_frame.pack(fill=tk.X, pady=5)

        # 关键词回复列表标题 + 启用开关
        keyword_title_frame = ttk.Frame(keyword_frame)
        keyword_title_frame.pack(anchor=tk.W, pady=5, fill=tk.X)
        ttk.Label(keyword_title_frame, text="当前关键词-回复列表：", style="功能标题.TLabel").pack(side=tk.LEFT)
        ttk.Checkbutton(
            keyword_title_frame,
            text="启用功能",
            variable=self.keyword_enabled,
            command=lambda: self._on_function_toggle("关键词@", self.keyword_enabled.get())
        ).pack(side=tk.RIGHT)

        keyword_list_frame = ttk.Frame(keyword_frame)
        keyword_list_frame.pack(fill=tk.X, pady=5)

        self.keyword_listbox = tk.Listbox(keyword_list_frame, height=4)
        self.keyword_listbox.config(font=("微软雅黑", 10), bg="#ffffff", fg="#333333")
        self.keyword_listbox.pack(side=tk.LEFT, fill=tk.X, expand=True)
        keyword_scrollbar = ttk.Scrollbar(keyword_list_frame, orient=tk.VERTICAL, command=self.keyword_listbox.yview)
        keyword_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
        self.keyword_listbox.config(yscrollcommand=keyword_scrollbar.set)

        # 关键词回复操作区
        keyword_ops_frame = ttk.Frame(keyword_frame)
        keyword_ops_frame.pack(fill=tk.X, pady=5)

        ttk.Label(keyword_ops_frame, text="关键词：").pack(side=tk.LEFT, padx=5)
        self.keyword_entry = ttk.Entry(keyword_ops_frame, width=20)
        self.keyword_entry.pack(side=tk.LEFT, padx=5)

        ttk.Label(keyword_ops_frame, text="回复话术（@%s代表用户名）：" % "").pack(side=tk.LEFT, padx=5)
        self.keyword_response_entry = ttk.Entry(keyword_ops_frame, width=40)
        self.keyword_response_entry.pack(side=tk.LEFT, padx=5, fill=tk.X, expand=True)

        ttk.Button(keyword_ops_frame, text="添加", command=self._add_keyword_response).pack(side=tk.LEFT, padx=2)
        ttk.Button(keyword_ops_frame, text="修改", command=self._edit_keyword_response).pack(side=tk.LEFT, padx=2)
        ttk.Button(keyword_ops_frame, text="删除", command=self._delete_keyword_response).pack(side=tk.LEFT, padx=2)
        # ttk.Button(keyword_ops_frame, text="测试匹配", command=self._test_keyword_match).pack(side=tk.LEFT, padx=2)

        # 初始化列表数据
        self._refresh_message_list("welcome")
        self._refresh_message_list("thank")
        self._refresh_keyword_list()

    def _on_function_toggle(self, function_name, is_enabled):
        """功能开关状态变化时的回调"""
        status = "启用" if is_enabled else "禁用"
        self.log_message(f"{function_name}功能已{status}")
        self.save_comprehensive_settings()  # 保存综合功能设置，开关启用的设置

        # 这里可以添加实际启用/禁用功能的逻辑
        # 例如：更新配置文件、暂停/启动相关线程等

    # ------------------- 查询相关方法 -------------------
    def do_query(self):
        """执行查询逻辑"""
        # 清除现有结果
        for item in self.result_tree.get_children():
            self.result_tree.delete(item)

        uid = self.query_uid_var.get().strip()
        uname = self.query_uname_var.get().strip()

        # 验证查询条件
        if not uid and not uname:
            messagebox.showwarning("提示", "请输入UID或用户名进行查询")
            return

        # 执行查询
        try:
            if uid:
                records = self.data_manager.query_by_uid(uid)   # 总计所有的月
                stats = self.data_manager.get_total_stats(uid=uid)   # 总计所有的月
            else:
                records = self.data_manager.query_by_uname(uname)  # 总计所有的月
                stats = self.data_manager.get_total_stats(uname=uname)  # 总计所有的月


            # print(records)
            # 显示结果
            for record in records:
                self.result_tree.insert("", tk.END, values=(
                    record.get("timestamp", ""),
                    record.get("uid", ""),
                    record.get("uname", ""),
                    record.get("result_gift_name", ""),
                    record.get("result_gift_num", 0),
                    record.get("cost", 0),
                    record.get("income", 0),
                    record.get("profit", 0)
                ))

            # 显示统计信息
            self.stats_var.set(
                f"共查询到 {len(records)} 条记录 | "
                f"总花费: {stats['总花费(gold)']} | "
                f"总收入: {stats['总收入(gold)']} | "
                f"总盈亏: {stats['总盈亏(gold)']}"
            )

            self.log_message(f"查询完成: UID={uid or '未指定'}, 用户名={uname or '未指定'}, 结果数={len(records)}")

        except Exception as e:
            messagebox.showerror("查询失败", f"查询过程中发生错误: {str(e)}")
            self.log_message(f"查询错误: {str(e)}")

    def clear_query(self):
        """清空查询条件和结果"""
        self.query_uid_var.set("")
        self.query_uname_var.set("")

        for item in self.result_tree.get_children():
            self.result_tree.delete(item)

        self.stats_var.set("请先执行查询...")

    def _create_log_tab(self):
        """创建日志选项卡"""
        self.log_frame = ttk.Frame(self.notebook, padding=10)
        self.notebook.add(self.log_frame, text="日志")

        self.log_text = scrolledtext.ScrolledText(self.log_frame, height=25)
        self.log_text.pack(fill=tk.BOTH, expand=True)
        self.log_text.config(state=tk.DISABLED, font=("Consolas", 10))

    def _bind_events(self):
        """绑定窗口事件"""
        # 窗口关闭事件（保存配置）
        self.root.protocol("WM_DELETE_WINDOW", self.on_close)
        # 定时更新下次发送时间显示
        self.update_next_send_time()

    def _load_config_to_widgets(self):
        """加载配置到GUI控件（修正监听房间ID的加载逻辑）"""
        # 1. 弹幕发送配置
        send_cfg = self.config_manager.send_settings
        self.room_ids_var.set(send_cfg.get("room_ids", ""))
        self.min_interval_var.set(str(send_cfg.get("min_interval", 10)))
        self.max_interval_var.set(str(send_cfg.get("max_interval", 30)))
        # 加载弹幕内容
        danmu_msgs = send_cfg.get("danmu_messages", [])
        if danmu_msgs:
            self.danmu_text.insert(tk.END, "\n".join(danmu_msgs))

        # 2. 礼物监听配置（核心修正：从Text组件插入内容，替代原listen_room_var）
        listener_cfg = self.config_manager.listener_settings
        listen_rooms = listener_cfg.get("listen_room_ids", [])
        if listen_rooms:
            # 用换行连接房间ID，适配多行文本框显示
            self.listen_room_text.insert(tk.END, "\n".join(listen_rooms))
        self.push_target_var.set(listener_cfg.get("push_target_room", ""))

        # 3.查询配置
        query_cfg = self.config_manager.query_settings
        self.query_lister_text_var.set(query_cfg.get("query_lister_text", ""))
        self.query_lister_text_enabled.set(query_cfg.get("enabled"))

        # 4.综合功能设置
        comprehensive_cfg = self.config_manager.comprehensive_settings
        self.welcome_enabled.set(comprehensive_cfg.get("welcome_message", "").get("enabled", ""))
        self.thank_enabled.set(comprehensive_cfg.get("thank_for_follow", "").get("enabled", ""))
        self.keyword_enabled.set(comprehensive_cfg.get("keyword_responses", "").get("enabled", ""))

        self.welcome_messages = comprehensive_cfg.get("welcome_message", "").get("list_of_scripts", "")
        self.thank_messages = comprehensive_cfg.get("thank_for_follow", "").get("list_of_scripts", "")
        self.keyword_responses = comprehensive_cfg.get("keyword_responses", "").get("list_of_scripts", "")


        self._refresh_message_list("welcome")
        self._refresh_message_list("thank")
        self._refresh_keyword_list()


    def save_query_settings(self,event=None):
        """保存查询设置"""
        query_cfg = {
            "enabled": self.query_lister_text_enabled.get(),
            "query_lister_text": self.query_lister_text_var.get().strip()
        }
        self.config_manager.query_settings = query_cfg
        self.log_message("查询设置已自动保存")

    def query_on_function_toggle(self, function_name, is_enabled):
        """功能开关状态变化时的回调"""
        status = "启用" if is_enabled else "禁用"
        self.log_message(f"{function_name}功能已{status}")
        self.save_query_settings() # 保存综合功能设置，开关启用的设置

    # ------------------- 登录相关方法 -------------------
    def import_cookie(self):
        """导入Cookie"""
        cookie_str = self.cookie_var.get().strip()
        success, msg = self.login_manager.import_cookie(cookie_str)
        if success:
            self.danmu_manager.update_cookies(self.login_manager.cookies, self.login_manager.csrf_token)
            self.update_login_status()
            self.log_message(f"Cookie导入成功: {msg}")
            messagebox.showinfo("成功", msg)
        else:
            self.log_message(f"Cookie导入失败: {msg}")
            messagebox.showerror("错误", msg)

    def save_cookie(self):
        """保存当前Cookie到CSV"""
        if not self.login_manager.cookies:
            messagebox.showerror("错误", "无可用Cookie（请先导入或登录）")
            return

        success, msg = self.login_manager.save_cookie_to_csv()
        if success:
            self.log_message(msg)
            messagebox.showinfo("成功", msg)
        else:
            self.log_message(f"保存Cookie失败: {msg}")
            messagebox.showerror("错误", msg)

    def test_cookie(self):
        """测试Cookie有效性"""
        success, msg = self.login_manager.test_cookie()
        if success:
            self.log_message(f"Cookie测试成功: {msg}")
            messagebox.showinfo("成功", msg)
        else:
            self.log_message(f"Cookie测试失败: {msg}")
            messagebox.showerror("错误", msg)

    def generate_qr_code(self):
        """生成二维码登录"""
        if self.login_manager.cookies:
            if messagebox.askyesno("提示", "已有登录状态，是否重新生成二维码登录？"):
                self.login_manager.clear_cookie()
                self.update_login_status()
            else:
                return

        success, msg = self.login_manager.generate_qr_code(self.qr_label)
        self.log_message(msg)

    def clear_cookie(self):
        """清除当前登录状态"""
        self.login_manager.clear_cookie()
        self.danmu_manager.update_cookies({}, "")
        self.update_login_status()
        self.log_message("已清除登录状态")

    # 登录相关方法（新增头像处理逻辑）
    def _load_avatar(self, url=None):
        """加载头像图片（支持网络URL和本地默认图）"""
        try:
            # 未登录时使用默认头像
            if not url:
                default_avatar = Image.new('RGB', (64, 64), color='#f0f0f0')
                self.avatar_photo = ImageTk.PhotoImage(default_avatar)
                self.avatar_label.config(image=self.avatar_photo)
                return

            # 已登录时下载并显示用户头像
            response = requests.get(url, timeout=10)
            response.raise_for_status()

            # 处理图片
            img = Image.open(BytesIO(response.content))
            img = img.resize((64, 64), Image.Resampling.LANCZOS)  # 高质量缩放
            self.avatar_photo = ImageTk.PhotoImage(img)

            # 保存头像到本地
            user_id = self.login_manager.cookies.get('DedeUserID', 'unknown')
            img.save(os.path.join(self.avatar_path, f"{user_id}.png"))

            # 显示头像
            self.avatar_label.config(image=self.avatar_photo)

        except Exception as e:
            self.log_message(f"头像加载失败: {str(e)}")
            # 加载失败时显示默认头像
            default_avatar = Image.new('RGB', (64, 64), color='#f0f0f0')
            self.avatar_photo = ImageTk.PhotoImage(default_avatar)
            self.avatar_label.config(image=self.avatar_photo)

    def update_login_status(self):
        """更新登录状态和头像显示"""
        if self.login_manager.cookies and 'DedeUserID' in self.login_manager.cookies:
            self.login_status_var.set("已登录")
            self.user_info_var.set(f"用户ID: {self.login_manager.cookies['DedeUserID']}")

            # 尝试获取头像（实际项目中需要从登录信息中获取头像URL）
            # avatar_url = f"https://i2.hdslb.com/bfs/face/80e154fae56f51f7a63bb3d43c2fb4372b01b0c8.jpg@240w_240h_1c_1s_!web-avatar-nav.avif"
            info = self.login_manager.get_user_info_with_cookie()
            result = json.loads(info)
            self._load_avatar(result['data']['avatar'])

            # self._load_avatar()  # 显示默认头像
        else:
            self.login_status_var.set("未登录")
            self.user_info_var.set("用户ID: 未登录")
            self._load_avatar()  # 显示默认头像

    # ------------------- 弹幕发送相关方法 -------------------
    def save_send_settings(self, event=None):
        """保存弹幕发送设置到配置"""
        send_cfg = {
            "room_ids": self.room_ids_var.get().strip(),
            "danmu_messages": self.danmu_text.get(1.0, tk.END).strip().split("\n"),
            "min_interval": int(self.min_interval_var.get()) if self.min_interval_var.get().isdigit() else 10,
            "max_interval": int(self.max_interval_var.get()) if self.max_interval_var.get().isdigit() else 30
        }
        self.config_manager.send_settings = send_cfg
        self.log_message("弹幕发送设置已自动保存")

    def start_sending(self):
        """开始自动发送弹幕"""
        # 验证登录状态
        if not self.login_manager.cookies:
            messagebox.showerror("错误", "请先登录（Cookie或二维码登录）")
            return

        # 验证房间ID
        room_ids = self.room_ids_var.get().strip()
        if not room_ids:
            messagebox.showerror("错误", "请输入发送目标房间ID")
            return
        valid_rooms = [rid for rid in room_ids.split(',') if rid.strip()]
        if not valid_rooms:
            messagebox.showerror("错误", "未检测到有效房间ID")
            return

        # 验证弹幕内容
        danmu_content = self.danmu_text.get(1.0, tk.END).strip()
        if not danmu_content:
            messagebox.showerror("错误", "请输入弹幕内容")
            return

        # 验证间隔时间
        try:
            min_interval = int(self.min_interval_var.get())
            max_interval = int(self.max_interval_var.get())
            if min_interval <= 0 or max_interval <= 0 or min_interval > max_interval:
                raise ValueError("最小间隔需小于等于最大间隔，且均为正数")
        except ValueError as e:
            messagebox.showerror("错误", f"间隔时间设置错误: {str(e)}")
            return

        # 启动发送线程
        self.is_sending = True
        self.start_send_btn.config(state=tk.DISABLED)
        self.stop_send_btn.config(state=tk.NORMAL)
        self.send_thread = threading.Thread(target=self.send_loop, daemon=True)
        self.send_thread.start()
        self.log_message(f"开始自动发送弹幕 | 目标房间: {', '.join(valid_rooms)}")

    def send_loop(self):
        """弹幕发送循环（子线程执行）"""
        danmu_list = self.danmu_text.get(1.0, tk.END).strip().split('\n')
        room_ids = [rid.strip() for rid in self.room_ids_var.get().split(',') if rid.strip()]
        min_interval = int(self.min_interval_var.get())
        max_interval = int(self.max_interval_var.get())

        while self.is_sending:
            try:
                # 随机选择弹幕和房间
                message = random.choice(danmu_list)
                room_id = random.choice(room_ids)
                sender = self.danmu_manager.get_sender(room_id)

                # 发送弹幕
                success, result = sender.send_danmu(message)
                if success:
                    self.log_message(f"房间{room_id}发送成功: {message[:20]}...")
                else:
                    self.log_message(f"房间{room_id}发送失败: {result}")

                # 计算下次发送时间
                wait_time = random.randint(min_interval, max_interval)
                self.next_send_time = datetime.datetime.now() + datetime.timedelta(seconds=wait_time)

                # 等待（可被中断）
                for _ in range(wait_time):
                    if not self.is_sending:
                        break
                    threading.Event().wait(1)

            except Exception as e:
                self.log_message(f"发送循环异常: {str(e)}")
                threading.Event().wait(10)  # 出错后等待10秒再重试

    def stop_sending(self):
        """停止自动发送弹幕"""
        self.is_sending = False
        self.start_send_btn.config(state=tk.NORMAL)
        self.stop_send_btn.config(state=tk.DISABLED)
        self.log_message("已停止自动发送弹幕")

    def test_sending(self):
        """测试发送单条弹幕"""
        if not self.login_manager.cookies:
            messagebox.showerror("错误", "请先登录")
            return

        room_ids = self.room_ids_var.get().strip()
        if not room_ids:
            messagebox.showerror("错误", "请输入房间ID")
            return
        first_room = room_ids.split(',')[0].strip()
        if not first_room:
            messagebox.showerror("错误", "未检测到有效房间ID")
            return

        danmu_content = self.danmu_text.get(1.0, tk.END).strip()
        if not danmu_content:
            messagebox.showerror("错误", "请输入弹幕内容")
            return
        first_msg = danmu_content.split('\n')[0]

        # 发送测试弹幕
        try:
            sender = self.danmu_manager.get_sender(first_room)
            success, result = sender.send_danmu(first_msg)
            if success:
                self.log_message(f"测试发送成功: {first_msg[:20]}...")
                messagebox.showinfo("成功", result)
            else:
                self.log_message(f"测试发送失败: {result}")
                messagebox.showerror("错误", result)
        except Exception as e:
            err_msg = f"测试发送异常: {str(e)}"
            self.log_message(err_msg)
            messagebox.showerror("错误", err_msg)

    def update_next_send_time(self):
        """定时更新下次发送时间显示"""
        if self.is_sending:
            if self.next_send_time:
                now = datetime.datetime.now()
                remaining = self.next_send_time - now
                if remaining.total_seconds() > 0:
                    mins, secs = divmod(math.ceil(remaining.total_seconds()), 60)
                    self.next_time_var.set(
                        f"下次发送时间: {self.next_send_time.strftime('%H:%M:%S')} (剩余: {mins}分{secs}秒)"
                    )
                else:
                    self.next_time_var.set("正在发送中...")
            else:
                self.next_time_var.set("下次发送时间: 准备中...")
        else:
            self.next_time_var.set("下次发送时间: 未开始")

        # 1秒后再次更新
        self.root.after(1000, self.update_next_send_time)

    # ------------------- 礼物监听相关方法（核心修正） -------------------
    def save_listener_settings(self, event=None):
        """保存礼物监听设置（从多行文本框获取内容，支持逗号/换行分隔）"""
        # 1. 从多行文本框获取内容：1.0表示第一行第一列，END表示末尾，strip()去除首尾空白
        listen_room_str = self.listen_room_text.get("1.0", tk.END).strip()
        # 2. 支持两种分隔方式：先按换行分割，再按逗号分割，最后过滤空值
        listen_rooms = []
        if listen_room_str:
            # 先按换行拆分成行，再按逗号拆分成单个ID
            lines = listen_room_str.split('\n')
            for line in lines:
                ids = [rid.strip() for rid in line.split(',') if rid.strip()]
                listen_rooms.extend(ids)
        # 3. 去重（避免重复监听同一房间）
        listen_rooms = list(set(listen_rooms))

        # 4. 保存配置
        listener_cfg = {
            "listen_room_ids": listen_rooms,
            "push_target_room": self.push_target_var.get().strip()
        }
        self.config_manager.listener_settings = listener_cfg
        self.log_message("礼物监听设置已自动保存")

    def start_listener(self):
        """启动礼物监听与推送（沿用原逻辑，内容已从多行文本框正确获取）"""
        if not self.login_manager.cookies:
            messagebox.showerror("错误", "请先登录（需SESSDATA Cookie）")
            return

        # 获取监听房间（从多行文本框解析，复用save方法的逻辑避免重复代码）
        listen_room_str = self.listen_room_text.get("1.0", tk.END).strip()
        listen_rooms = []
        if listen_room_str:
            lines = listen_room_str.split('\n')
            for line in lines:
                ids = [rid.strip() for rid in line.split(',') if rid.strip()]
                listen_rooms.extend(ids)
        listen_rooms = list(set(listen_rooms))  # 去重

        push_target = self.push_target_var.get().strip()

        if not listen_rooms:
            messagebox.showerror("错误", "请输入监听房间ID")
            return
        if not push_target:
            messagebox.showerror("错误", "请输入推送目标房间ID")
            return

        query_cfg = self.config_manager.query_settings
        query_lister_text = query_cfg.get("query_lister_text", "")

        # 关注主播话术列表 和 进入直播间话术列表 是否启用



        # 创建监听实例并启动
        self.gift_listener = GiftListener(
            config_manager=self.config_manager,
            query_lister_text=query_lister_text,
            listen_room_ids=listen_rooms,
            push_target_room=push_target,
            danmu_manager=self.danmu_manager,
            log_callback=self.log_message
        )
        self.gift_listener.start_listen()
        self.start_listen_btn.config(state=tk.DISABLED)
        self.stop_listen_btn.config(state=tk.NORMAL)

    def stop_listener(self):
        """停止礼物监听与推送"""
        if self.gift_listener:
            self.gift_listener.stop_listen()
            self.gift_listener = None
        self.start_listen_btn.config(state=tk.NORMAL)
        self.stop_listen_btn.config(state=tk.DISABLED)

    # ------------------- 日志与窗口相关方法 -------------------
    def log_message(self, message: str):
        """添加日志消息"""
        self.log_text.config(state=tk.NORMAL)
        timestamp = get_current_time()
        self.log_text.insert(tk.END, f"[{timestamp}] {message}\n")
        self.log_text.see(tk.END)  # 滚动到最新日志
        self.log_text.config(state=tk.DISABLED)
        self.status_var.set(message)  # 更新状态栏

    def on_close(self):
        """窗口关闭时保存配置"""
        # 保存窗口大小
        self.config_manager.gui_settings = {
            **self.config_manager.gui_settings,
            "window_geometry": self.root.geometry(),
            "selected_tab": self.notebook.index(self.notebook.select())
        }

        # 停止所有后台任务
        self.stop_sending()
        self.stop_listener()

        # 关闭窗口
        self.root.destroy()

    # ------------------- 综合功能相关方法 -------------------
    # 话术管理通用方法（进场欢迎和关注感谢）
    def _refresh_message_list(self, msg_type):

        """刷新话术列表"""
        listbox, messages = self._get_msg_objects(msg_type)
        listbox.delete(0, tk.END)
        for idx, msg in enumerate(messages, 1):
            listbox.insert(tk.END, f"{idx}. {msg}")

    def _get_msg_objects(self, msg_type):
        """获取对应类型的列表框和消息列表"""
        if msg_type == "welcome":
            return self.welcome_listbox, self.welcome_messages
        elif msg_type == "thank":
            return self.thank_listbox, self.thank_messages

    def _add_message(self, msg_type):
        """添加新话术"""
        entry, messages = self._get_msg_entry_and_list(msg_type)
        new_msg = entry.get().strip()


        if not new_msg:
            messagebox.showwarning("输入错误", "话术内容不能为空！")
            return

        messages.append(new_msg)
        entry.delete(0, tk.END)
        self._refresh_message_list(msg_type)
        self.save_comprehensive_settings()
        messagebox.showinfo("添加成功", "话术已成功添加！")



    def _edit_message(self, msg_type):
        """修改选中的话术"""
        listbox, messages = self._get_msg_objects(msg_type)
        entry = self._get_msg_entry(msg_type)
        selected = listbox.curselection()

        if not selected:
            messagebox.showwarning("选择错误", "请先选中要修改的话术！")
            return

        index = selected[0]
        new_msg = entry.get().strip()

        if not new_msg:
            messagebox.showwarning("输入错误", "话术内容不能为空！")
            return

        messages[index] = new_msg
        entry.delete(0, tk.END)

        self._refresh_message_list(msg_type)
        self.save_comprehensive_settings()
        messagebox.showinfo("修改成功", "话术已成功更新！")

    def _delete_message(self, msg_type):
        """删除选中的话术"""
        listbox, messages = self._get_msg_objects(msg_type)
        selected = listbox.curselection()

        if not selected:
            messagebox.showwarning("选择错误", "请先选中要删除的话术！")
            return

        if messagebox.askyesno("确认删除", "确定要删除选中的话术吗？"):
            index = selected[0]
            del messages[index]
            self._refresh_message_list(msg_type)
            self.save_comprehensive_settings()
            messagebox.showinfo("删除成功", "话术已成功删除！")

    def _test_random_message(self, msg_type):
        """随机选择一条话术进行测试"""
        _, messages = self._get_msg_objects(msg_type)

        if not messages:
            messagebox.showwarning("没有数据", "请先添加话术内容！")
            return

        import random
        selected_msg = random.choice(messages)
        messagebox.showinfo("随机话术测试", f"随机选中的话术：\n{selected_msg}")

    def _get_msg_entry_and_list(self, msg_type):
        """获取对应类型的输入框和消息列表"""
        if msg_type == "welcome":
            return self.welcome_entry, self.welcome_messages
        elif msg_type == "thank":
            return self.thank_entry, self.thank_messages

    def _get_msg_entry(self, msg_type):
        """获取对应类型的输入框"""
        if msg_type == "welcome":
            return self.welcome_entry
        elif msg_type == "thank":
            return self.thank_entry

    # 关键词回复管理方法（增强功能）
    def _refresh_keyword_list(self):

        """刷新关键词-回复列表"""
        self.keyword_listbox.delete(0, tk.END)
        for idx, (keyword, response) in enumerate(self.keyword_responses.items(), 1):
            # 显示时截断过长的回复，保持列表整洁
            display_response = response[:30] + "..." if len(response) > 30 else response
            self.keyword_listbox.insert(tk.END, f"{idx}. 关键词: {keyword} → 回复: {display_response}")

    def _add_keyword_response(self):
        """添加关键词-回复对"""
        keyword = self.keyword_entry.get().strip()
        response = self.keyword_response_entry.get().strip()

        if not keyword or not response:
            messagebox.showwarning("输入错误", "关键词和回复内容都不能为空！")
            return

        if keyword in self.keyword_responses:
            if not messagebox.askyesno("已存在", f"关键词 '{keyword}' 已存在，是否更新其回复内容？"):
                return

        self.keyword_responses[keyword] = response
        self.keyword_entry.delete(0, tk.END)
        self.keyword_response_entry.delete(0, tk.END)

        self._refresh_keyword_list()
        self.save_comprehensive_settings()


        messagebox.showinfo("添加成功", f"关键词 '{keyword}' 已成功添加/更新！")

    def _edit_keyword_response(self):
        """修改选中的关键词-回复对"""
        selected = self.keyword_listbox.curselection()
        if not selected:
            messagebox.showwarning("选择错误", "请先选中要修改的关键词-回复对！")
            return

        index = selected[0]
        keywords = list(self.keyword_responses.keys())
        selected_keyword = keywords[index]
        selected_response = self.keyword_responses[selected_keyword]

        # 填充到输入框
        self.keyword_entry.delete(0, tk.END)
        self.keyword_entry.insert(0, selected_keyword)
        self.keyword_response_entry.delete(0, tk.END)
        self.keyword_response_entry.insert(0, selected_response)

    def _delete_keyword_response(self):
        """删除选中的关键词-回复对"""
        selected = self.keyword_listbox.curselection()
        if not selected:
            messagebox.showwarning("选择错误", "请先选中要删除的关键词-回复对！")
            return

        index = selected[0]
        keywords = list(self.keyword_responses.keys())
        selected_keyword = keywords[index]

        if messagebox.askyesno("确认删除", f"确定要删除关键词 '{selected_keyword}' 及其回复吗？"):
            del self.keyword_responses[selected_keyword]
            self._refresh_keyword_list()
            self.save_comprehensive_settings()
            messagebox.showinfo("删除成功", f"关键词 '{selected_keyword}' 已成功删除！")

    def _test_keyword_match(self):
        """测试关键词匹配效果"""
        test_text = simpledialog.askstring("关键词测试", "请输入测试文本:")
        if not test_text:
            return

        matched = False
        result = []

        # 检查是否匹配任何关键词
        for keyword, response in self.keyword_responses.items():
            if keyword in test_text:
                matched = True
                # 替换@%s为测试用户
                test_user = "测试用户"
                formatted_response = response % test_user if "@%s" in response else response
                result.append(f"匹配关键词: '{keyword}' → 回复: {formatted_response}")

        if matched:
            messagebox.showinfo("匹配结果", "\n".join(result))
        else:
            messagebox.showinfo("匹配结果", "未匹配到任何关键词")

    def find_keyword_response(self, text, username):
        """实际应用中调用此方法查找关键词并返回回复"""
        for keyword, response in self.keyword_responses.items():
            if keyword in text:
                # 替换@%s为实际用户名
                return response % username if "@%s" in response else response
        return None

    def save_comprehensive_settings(self, event=None):
        """保存弹幕发送设置到配置"""
        comprehensive_cfg = {
            "thank_for_follow": {
                "enabled": self.thank_enabled.get(), # 获取布尔值,
                "list_of_scripts": self.thank_messages,
            },
            "welcome_message": {
                "enabled": self.welcome_enabled.get(), # 获取布尔值,
                "list_of_scripts":self.welcome_messages,
            },
            "keyword_responses": {
                "enabled": self.keyword_enabled.get(),
                "list_of_scripts": self.keyword_responses,
            }
        }
        self.config_manager.comprehensive_settings = comprehensive_cfg
        self.log_message("综合功能设置设置已自动保存")